package com.xpec.c4.db.usertype;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;

import com.ms.db.usertype.BasicToString;
import com.xpec.c4.db.util.CodecTool;


public class MapIntegerBooleanToString extends BasicToString {
	
	/**
	 *
	 */
	private static final long serialVersionUID = 6831514659485318688L;

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {

		if (x != null && y != null) {
			Map<?, ?> xMap = (Map<?, ?>) x;
			Map<?, ?> yMap = (Map<?, ?>) y;
			if (xMap.size() != yMap.size())
				return false;
			Set<?> keys = xMap.keySet();
			for (Object key : keys) {
				Object str1 = xMap.get(key);
				Object str2 = yMap.get(key);
				if (!str1.equals(str2))
					return false;
			}
			return true;
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected String assemble(Object obj) {
		Map<Integer,Boolean> map = (Map<Integer,Boolean>) obj;
		StringBuilder sb = new StringBuilder();
		Set<Integer> keys = map.keySet();
		for (Object key : keys) {
			sb.append(key + SPLITTER);
			CodecTool.append(sb, map.get(key), SPLITTER);
		}
		if (sb.length() > 0) {
			sb.setLength(sb.length() - 1);
		}
		return sb.toString();
	}

	@Override
	protected Object parse(String value) {
		if(value==null){
			return null;
		}
		Map<Integer,Boolean> map = new HashMap<Integer,Boolean>();
		if (!(value.length() > 0)) {
			return map;
		}
		String[] strs = CodecTool.split(value, SPLITTER);

		for (int i = 0; i < strs.length; i += 2) {
			map.put(Integer.valueOf(strs[i]), CodecTool.getBoolean(strs[i + 1]));
		}
		return map;
	}

	@Override
	public Class<?> returnedClass() {
		return Map.class;
	}

	@Override
	public int[] sqlTypes() {
		return CLOB_TYPES;
	}

}
